import { api } from '../../utils/api';

interface IAppOption {
  globalData: {
    user: any;
  };
}

Page({
  data: {
    username: '',
    password: '',
    isLogin: true, // true: 登录模式, false: 注册模式
  },

  onLoad() {
    // 检查是否已登录
    const token = wx.getStorageSync('token');
    if (token) {
      wx.redirectTo({
        url: '/pages/chat-list/chat-list',
      });
    }
  },

  onUsernameInput(e: any) {
    this.setData({
      username: e.detail.value,
    });
  },

  onPasswordInput(e: any) {
    this.setData({
      password: e.detail.value,
    });
  },

  switchMode() {
    this.setData({
      isLogin: !this.data.isLogin,
      username: '',
      password: '',
    });
  },

  async handleSubmit() {
    const { username, password, isLogin } = this.data;

    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none',
      });
      return;
    }

    wx.showLoading({
      title: isLogin ? '登录中...' : '注册中...',
    });

    try {
      let res: any;
      if (isLogin) {
        res = await api.login(username, password);
      } else {
        res = await api.register(username, password);
      }

      if (res.success) {
        // 登录成功，获取用户信息并存入缓存
        try {
          const userRes: any = await api.getCurrentUser();
          if (userRes.success && userRes.user) {
            // 将用户信息存入缓存
            wx.setStorageSync('currentUser', userRes.user);
            // 更新全局数据
            const app = getApp<IAppOption>();
            app.globalData.user = userRes.user;
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
        }
        
        wx.hideLoading();
        wx.showToast({
          title: isLogin ? '登录成功' : '注册成功',
          icon: 'success',
        });
        
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/chat-list/chat-list',
          });
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.message || (isLogin ? '登录失败' : '注册失败'),
          icon: 'none',
        });
      }
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '网络错误',
        icon: 'none',
      });
    }
  },
});

